package cn.itcat.bos.web.action;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import javax.jms.JMSException;
import javax.jms.MapMessage;
import javax.jms.Message;
import javax.jms.Session;
import javax.ws.rs.core.MediaType;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.shiro.web.util.WebUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.jms.core.MessageCreator;
import org.springframework.stereotype.Controller;

import cn.itcast.bos.domain.constant.Constants;
import cn.itcast.crm.domain.Customer;
import cn.itcat.bos.utils.MailUtils;
@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class CustomerAction extends BaseAction<Customer>{
	@Autowired
	@Qualifier("jmsQueueTemplate")
	private JmsTemplate jmsTemplate;
	
	@Action(value="customer_sendsms")
	public String sendSms() throws Exception{
		//手机已保存到Customer中
		//生成验证码
		String random = RandomStringUtils.randomNumeric(4);
		//将验证码存入session中
		ServletActionContext.getRequest().getSession().
		setAttribute(model.getTelephone(), random);
		System.out.println("yanzhengma:"+random);
		//编辑短信内容
		final String msg = "尊敬的用户您好，本次获取的验证码为："+ random + ",服务电话：4006184000";
		
		jmsTemplate.send("bos_sms",new MessageCreator() {
			
			@Override
			public Message createMessage(Session session) throws JMSException {
				MapMessage mapMessage = session.createMapMessage();
				mapMessage.setString("telephone",model.getTelephone());
				mapMessage.setString("msg",msg);
				return mapMessage;
			}
		});
		
		return NONE;
		
		
//		//调用SMS服务发送短信
////		String result=SmsUtils.sendSmsByHTTP(model.getTelephone(), msg);
//		String result="000/xxx";
//		if(result.startsWith("000")){
//		return NONE;
//		}else{
//			throw new RuntimeException("短信发送失败，信息码是："+result);
//		}
	}
	private String checkcode;
	
	public void setCheckcode(String checkcode) {
		this.checkcode = checkcode;
	}
	
	@Autowired
	private RedisTemplate<String, String> redisTemplate;
	
	
	@Action(value="customer_regist",results={
			@Result(name="success",type="redirect",location="signup-success.html"),
			@Result(name="input",type="redirect",location="signup.html")})
	public String regist(){
		
		String codeSession=(String) ServletActionContext.getRequest().
				getSession().getAttribute(model.getTelephone());
		
		if(checkcode == null || !checkcode.equals(codeSession)){
			System.out.println("djfdif");
			return INPUT;
		}
		
		WebClient.create("http://localhost:9002/crm_management/"
				+ "services/customerService/customer").
		type(MediaType.APPLICATION_JSON).post(model);
		System.out.println("注册成功。。。。。");
		//生成激活码
		String activecode=RandomStringUtils.randomNumeric(32);
		//将激活码存入redis中
		redisTemplate.opsForValue().set(model.getTelephone(), activecode, 24, TimeUnit.HOURS);
		
		String content= "尊敬的用户你好，请在24小时内，进行邮箱账户的绑定，请点击下面地址完成绑定:<br/><a href='"
				+ ""+MailUtils.activeUrl+"?telephone="+model.getTelephone()
				+"&activecode="+activecode+"'>速运快递激活地址</a>";
		MailUtils.sendMail("速运快递邮箱激活码", content, model.getEmail(), activecode);
		return SUCCESS;
	}
	
	
	private String activecode;
	
	
	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}


	@Action(value="customer_activeMail")
	public String activemail() throws IOException{
		ServletActionContext.getResponse().setContentType("text/html;charset=UTF-8");
		//获得激活码
		String activecodeRedis= redisTemplate.opsForValue().get(model.getTelephone());
		if(activecodeRedis==null || !activecodeRedis.equals(activecode)){
			//激活码无效
			ServletActionContext.getResponse().getWriter()
			.println("激活码无效，请登录系统，重新获取激活码");
		}else{
			//激活码有效
			//获得对象
			Customer customer= WebClient.create("http://localhost:9002/crm_management/"
				+ "services/customerService/customer/telephone/"+model.getTelephone())
					.accept(MediaType.APPLICATION_JSON).get(Customer.class);
			if(customer.getType()==null ||customer.getType() !=1){
				WebClient.create("http://localhost:9002/crm_management/"
						+ "services/customerService/customer/updatetype/"+model.getTelephone())
				.put(customer);
				ServletActionContext.getResponse().getWriter()
				.println("邮箱绑定成功");
			}else{
				ServletActionContext.getResponse().getWriter()
				.println("已绑定过邮箱，请勿重复绑定");
			}
		}
		
		redisTemplate.delete(model.getTelephone());
		return NONE;
	}
	
	@Action(value="customer_login",results={
			@Result(name="login",location="login.html",type="redirect"),
			@Result(name="success",location="index.html#/myhome",type="redirect")})
	public String login(){
		Customer customer = WebClient.create(Constants.CRM_MANAGEMENT_URL
						+ "services/customerService/customer/login?telephone="
				+model.getTelephone()+"&password="+model.getPassword()).accept(MediaType.APPLICATION_JSON).get(Customer.class);
		if(customer==null){
			return LOGIN;
		}else{
			ServletActionContext.getRequest().setAttribute("customer", customer);
			return SUCCESS;
		}
	}
	
}
